<?php
namespace app_supplier\helpers;

use Yii;
use yii\db\Query;
use yii\data\Pagination;
use yii\data\Sort;
use yii\helpers\ArrayHelper;
use app_supplier\models\StorePurchasingDemand;
use yii\caching\DbDependency;

class PurchaseHelper
{
    public static $CACHE_TIME = 60*60*60;#cache time
    public static $CACHING_TIME = 60*60;#cache time

    /**获取列表
     * @param $params
     * @param array $where
     * @param array $andWhere
     * @param array $orWhere
     * @return array
     */
    public static function getList($params, $where = [], $andWhere = [], $orWhere = [], $my_list = null)
    {
        $key = '';
        $my_list_where = [];
        $sort = [
            'desc'=>SORT_DESC,
            'asc'=>SORT_ASC
        ];
        $group = 'm.id';
        $params = self::getParams($params);

        $nowDate = date('Y-m-d H:i:s');

        $fields = [
            's.id','m.id as m_id', 's.store_id', 's.dealer_number', 's.user_id', 's.mobile', 's.address', 's.status', 's.describe', 's.demand_time', 's.user_name', 's.create_time',
            'm.dpd_id','m.material_brand', 'm.material_version' ,'m.dealer_id', 'm.car_type', 'm.material_name', 'm.dealer_material_type', 'm.material_number', 'm.material_price',
            //'d.user_id as dealer_user_id',
            "(to_days(s.demand_time)-to_days('{$nowDate}')) as days"
        ];
        //正确的字段
        $fieldContrastTrue = [
            'status'=>'s.status',
            'cmbProvince'=>'s.cmbProvince',
            'cmbCity'=>'s.cmbCity',
            'cmbArea'=>'s.cmbArea',
        ];

        $query = (new Query())
            ->select($fields)
            ->from('store_purchasing_demand s')
            ->join('INNER JOIN', 'store_purchasing_material m', 's.id = m.dpd_id');
            //->join('RIGNHT JOIN', 'dealer_purchasing_material d', 'd.dpd_id=s.id and d.dealer_id=s.store_id');
        if (!empty($my_list)) {
            $query->join('INNER JOIN', 'dealer_purchasing_material as t', 't.dpd_id=s.id');
            if ($my_list == 1) {
                $key = 1;
                $my_list_where = ['t.state'=>0];
            }
            if ($my_list == 2) {
                $key = 2;
                $my_list_where = ['t.state'=>1];
            }
        }
        if ($my_list_where) {
            $query->andWhere($my_list_where);
            $query->addSelect('t.state');
        }
        if (!empty($where) && is_array($where)) {
            $str = [];
            $condition = [];
            $status_flag = true;
            $address_flag = true;
            $whereStatus = [];
            foreach ($where as $key=>$value) {

                if (in_array($key, [ 'cmbArea', 'cmbCity', 'cmbProvince'])) {
                    $address_flag = false;
                    $query->addSelect("{$fieldContrastTrue[$key]} as address_city");
                } else {
                    if (!in_array("{$fieldContrastTrue['cmbProvince']} as address_city", $query->select)) {
                        if ($address_flag) {
                            $query->addSelect("{$fieldContrastTrue['cmbProvince']} as address_city");
                        }
                    }
                    if ($key=='status' && intval($value)===2) {
                        //查询过期订单
                        $now = date('Y-m-d H:i:s');
                        $whereStatus  = ['<', 's.demand_time', $now];
                        $status_flag = false;
                    }
                }
                if ($key === 'status') {
                    if ($status_flag) {
                        $str[] =  "{$fieldContrastTrue[$key]}=:{$key}";
                        $condition[":{$key}"]=$value;
                    }
                } else {
                    $str[] =  "{$fieldContrastTrue[$key]}=:{$key}";
                    $condition[":{$key}"]=$value;
                }
            }
            $query->where(implode(' and ',$str), $condition);
            if (!empty($whereStatus)) {
                $query->andWhere($whereStatus);
            }
        } else {
            $query->addSelect("{$fieldContrastTrue['cmbProvince']} as address_city");
        }
        if (!empty($andWhere) && is_array($andWhere)) {
            foreach ($andWhere as $k=>$v) {
               if (empty($v['end'])) {
                   $query->andFilterCompare('s.demand_time', "> {$v['start']}");
               } else {
                   $query->andWhere(["{$k}", 's.demand_time', "{$v['start']}", "{$v['end']}"]);
               }
            }
        }
        //group by
        $query->groupBy($group);
        //page
        $page = new Pagination([
            'totalCount' =>$query->count(),
            'pageSize' => $params['page']['pageSize']
        ]);
        $page->setPage($params['page']['page']-1);
        $page->route = $params['page']['url'];

        //order by
        if (isset($params['sort']) && !empty($params['sort'])) {
            foreach ($params['sort'] as $k=>$v) {
                $query->orderBy([
                    "{$k}"=>$sort[strtolower($v)]
                ]);
            }
        }
        //limit
        //var_dump($query->createCommand()->getRawSql());
        $query->offset($page->offset);
        $query->limit($page->limit);
        $row = array_map(function ($recode) {
            $recode['status_info'] = self::getOrderState('order_state', $recode['status'])['name'];
            $recode['demand_time'] = substr($recode['demand_time'], 0, strlen(date('Y-m-d')));
            if( isset($recode['days']) && $recode['days'] < 0) {
                self::updateStatus($recode['id'], 2);
                $recode['status_info'] = '过期订单';
            }
            //$recode['create_time'] = substr($recode['create_time'], 0,strlen(date('Y-m-d')));
            return $recode;
        }, $query->all());

        $list = [
            'list'=>$row,
            'page'=>$page
        ];

        return $list;
    }

    /**发回前端报价状态， 订单状态
     * @return mixed
     */
    public static function getOrderState($key = null, $id = 0)
    {
        $list['order_state'] =  [
            [
                'id'=>0,
                'name'=>'所有订单'
            ],
            [
                'id'=>1,
                'name'=>'发布中订单'
            ],
            [
                'id'=>2,
                'name'=>'过期订单'
            ],

        ];
        $list['price_list'] = [
            [
                'id'=>0,
                'name'=>'所有订单'
            ],
            [
                'id'=>1,
                'name'=>'已经报价'
            ],
            [
                'id'=>2,
                'name'=>'还未报价'
            ],
        ];
        if (!empty($key)) {
            if (isset($list[$key]) && !empty($list[$key]) && is_array($list[$key])) {
                foreach ($list[$key] as $k=>$v) {
                    if ($v['id']===intval($id)) {
                        return $v;
                    } else {
                        continue;
                    }
                }
                return [];
            } else {
                return null;
            }
        }
        return $list;
    }
    /**判断用户是否已报价
     * @param $user_id
     * @return array|bool
     */
    public static function getDealerUser($mid, $did, $dealer_id, $user_id)
    {
        //'dpd_id','dealer_id', 'user_id'
        $query = (new Query())
            ->select(['state', ])
            ->from('dealer_purchasing_material')
            ->where('d_m_id=:d_m_id and dealer_id=:dealer_id and dpd_id=:dpd_id and user_id=:user_id', [':d_m_id'=>$mid, ':dpd_id'=>$did, ':dealer_id'=>$dealer_id, ':user_id'=>$user_id])
            ->one();
       if (!empty($query)) {
           if ($query['state'] == 1) {
               return null;
           } else {
               return $query;
           }
       } else {
           return null;
       }
    }
    /**获取参数
     * @param $params
     * @return array
     */
    public static function getParams($params)
    {
        return array_merge([
            'sort'=>[
                'create_time'=>'desc'
            ],
            'page'=>[
                'page'=>1,
                'pageSize'=>2,
            ],
        ], $params);
    }

    /**获取时间区间
     * @param string $date
     * @return array
     */
    public static function formatDate($date = 'today')
    {
        $time = [];
        switch ($date) {
            case 'today':
                $time = [
                    'start'=>date('Y-m-d') . ' 00:00:00',
                    'end'=>date('Y-m-d') . ' 23:59:59',
                ];
                break;
            case 'week':
                $time = [
                    'start'=>date('Y-m-d H:i:s', mktime(0,0,0,date( "m"), date( "d") - date( "w",time()),date( "Y"))),
                    'end'=>date('Y-m-d H:i:s',mktime(23,59,59,date( "m"), date( "d") - date( "w",time()) + 6,date( "Y"))),
                ];
                break;
            case 'mouth':
                $time = [
                    'start'=>date('Y-m-d H:i:s', mktime(0, 0, 0, date("m",time()), 1, date("Y",time()))),
                    'end'=>date('Y-m-d H:i:s', mktime(23, 59, 59, date("m",time()),date('t'), date("Y",time()))),
                ];
                break;
        }

        return $time;
    }

    /**过滤where的数据：去除时间
     * @param array $arg
     * @return array
     */
    public static function disposeArguments($arg = [])
    {

        //$arg['cmbCity']=;
        $temp = [];
        if (empty($arg)) return [];
        if (is_array($arg)) {
            if (isset($arg['cmbProvince']) && $arg['cmbProvince']=='全国') {
                $arg['cmbProvince'] = null;
                $arg['cmbCity'] = null;
                $arg['cmbArea'] = null;
            } else {
                if (isset($arg['cmbCity']) && $arg['cmbCity']=='全地级市'){
                    $arg['cmbCity'] = null;
                    $arg['cmbArea'] = null;
                } elseif(isset($arg['cmbCity']) && $arg['cmbCity']=='市辖区') {
                    if (isset($arg['cmbArea']) && $arg['cmbArea'] == '全区-全县') {
                        $arg['cmbCity'] = null;
                        $arg['cmbArea'] = null;
                    } else {
                        $arg['cmbCity'] = null;
                        $arg['cmbProvince'] = null;
                    }
                } else {
                    if (isset($arg['cmbArea']) && $arg['cmbArea'] == '全区-全县') {
                        $arg['cmbProvince'] = null;
                        $arg['cmbArea'] = null;
                    } else {
                        $arg['cmbProvince'] = null;
                        $arg['cmbCity'] = null;

                    }
                }
            }
            if (isset($arg['price_status'])) {
                $arg['price_status'] = null;
            }
            foreach ($arg as $k=>$v) {
                if (!empty($v) && $v && !in_array($k, ['time', 'end', 'start'])) {
                    $temp[$k] = $v;
                }
            }
            return $temp;
        } else {
            return [];
        }
    }

    /**获取时间期间
     * @param array $arg
     * @return array
     */
    public static function disposeAndWhere($arg = [])
    {
        $temp = [];
        if (empty($arg)) return [];
        if (is_array($arg)) {
            foreach ($arg as $k=>$v) {
                if (in_array($k, ['time'])) {
                    $date = self::formatDate($v);
                    if (!empty($date)) {
                        $temp = [
                            'between'=>[
                                'start'=>$date['start'],
                                'end'=>$date['end']
                            ]
                        ];
                    } else {
                        if ($v != 'all') {
                            $temp = [
                                'between'=>[
                                    'start'=>!empty($arg['start']) ? $arg['start'] .' 00:00:00' : date('Y-m-d') . ' 00:00:00',
                                    'end'=>!empty($arg['end']) ? $arg['end'] .' 23:59:59' : null,
                                ]
                            ];
                        }
                    }
                }
            }
            return $temp;
        } else {
            return [];
        }
    }

    /**过滤筛选条件
     * @param array $arg
     * @return array
     */
    public static function FilterArguments($arg = [])
    {
        $temp = [];
        if (empty($arg)) return [];
        if (is_array($arg)) {
            foreach ($arg as $k=>$value) {
                if (in_array($k, ['cmbProvince', 'cmbArea','cmbCity', 'start', 'end', 'status', 'time'])) {
                    $temp[$k] = $value;
                }
            }
            return $temp;
        } else {
            return [];
        }
    }

    /**构造排序的url
     * @param $url
     * @param string $order
     * @return array
     */
    public static function groupSortUrl($fields,$url, $order = 'desc')
    {
        $sortUrl = [];
        if ($order == 'asc') {
            $order = 'desc';
        } elseif($order == 'desc') {
            $order = 'asc';
        } else {
            $order='desc';
        }
        foreach ($fields as $row) {
            if (strpos($url, 'sort=')!==false) {
                $tempUrl = preg_replace("/sort=\w{1,}&order=\w{1,}/", "sort={$row}&order={$order}", $url);
                $sortUrl[$row] = $tempUrl;
            } else {
                if (strpos($url, "?") !== false) {
                    $temp = "&sort={$row}&order={$order}";
                    $sortUrl[$row] = $url.$temp;
                } else {
                    $t = "?sort={$row}&order={$order}";
                    $sortUrl[$row] = $url.$t;
                }
            }

        }
        return $sortUrl;
    }

    /**
     * 获取车型
     */
    public static function carType()
    {
        $key = md5('car_type');
        $list = Yii::$app->cache->get($key);
        if ($list === false) {
            $list = (new Query())
                ->select(['category_id', 'name'])
                ->from('cart1_category')
                ->offset(0)
                ->limit(100)
                ->all();
            Yii::$app->cache->set($key, $list, self::$CACHE_TIME);
        }
        return $list;
    }

    /**
     * 获取材料
     */
    public static function material()
    {
        $key = md5('material_list');
        $list = Yii::$app->cache->get($key);
        if ($list === false) {
            $list = (new Query())
                ->select(['id', 'name'])
                ->from('material')
                ->all();
            Yii::$app->cache->set($key, $list, self::$CACHE_TIME);
        }
       return  $list;
    }

    /**
     * 获取材料品牌
     */
    public static function brand($material_id = 0)
    {
        $key = md5('brand_list_'.$material_id);
        $brand = Yii::$app->cache->get($key);
        if ($brand === false) {
            $query = (new Query())
                ->select(['material_id','brand'])
                ->from('material_type');
            if ($material_id != 0) {
                $query->where('material_id=:id', [':id'=>$material_id]);
            }
            $brand =  $query->groupBy('brand')->all();
            Yii::$app->cache->set($key, $brand, self::$CACHE_TIME);
        }
       return $brand;
    }

    /**获取车类型
     * @param int $parentID
     * @param string $latter
     * @return array
     */
    public static function getCatType($parentID = 0, $latter = '')
    {
        if ($parentID <= 0) {
            $sql = "SELECT category_id as id, image, pinyin_i as latter, name, is_hot as hot 
                    FROM cart1_category 
                    WHERE parent_id=0  
                    AND status = '1' and type=0 ";
            if (!empty($latter)) {
                $sql .= " and pinyin_i='{$latter}'";
            }
            $sql .= " order by sort_order, LCASE(name)";
        }
        else {
            $sql = "SELECT category_id as id,name 
                    FROM cart1_category 
                    WHERE parent_id={$parentID} 
                    AND status = '1'  and type=0
                    ORDER BY sort_order, LCASE(name) ";
        }

        if(isset($_GET["others"]))
        {
            $sql = "SELECT category_id as id, image, pinyin_i as latter, name, is_hot as hot
                    FROM cart1_category
                    WHERE parent_id=0
                    AND status = '1' and type=1 ";
        }
        return Yii::$app->db->createCommand($sql)->queryAll();
    }
    /**
     * 获取配件消耗列表
     */
    public static  function materialExpendList($params, $where = [], $andWhere = [], $orWhere = [])
    {

        $key = '';
        $sort = [
            'desc'=>SORT_DESC,
            'asc'=>SORT_ASC
        ];
        $group = [
            'mt.type'
        ];
        $fieldContrastTrue = [
            'create_time'=>'o.create_time',
            'complete_time'=>'o.create_time',
            'material'=>'mt.material_id',
            'brand'=>'mt.brand',
            'car_type'=>'o.user_car',
            'cmbProvince'=>'s.province',
            'cmbCity'=>'s.city',
            'cmbArea'=>'s.district',
        ];
        $params = self::getParams($params);
        $key = $params['sortField'].$params['order'].$params['page']['page'];
        //fields
        $fields =[
            'o.complete_time',
            'o.create_time',
            'i.material_id',
            //'i.material_type',
            'o.user_car',
            'm.name as material_name',
            'mt.type as material_type',
            'mt.brand'
        ];
        $query = (new Query())
            ->select($fields)
            ->from('order as o')
            ->join('inner join', 'order_item i', 'o.order_number=i.order_number')
            ->join('left join ', 'store s', 'o.store_id=s.id')
            ->join('left join ', 'material_type mt', 'mt.id=i.material_type_id')
            ->join('left join ', 'material m', 'm.id=mt.material_id');

        //where
        if (!empty($where) && is_array($where)) {
            $str = [];
            $condition = [];
            $address_flag = true;
            foreach ($where as $k=>$w) {
                if (in_array($k, ['cmbProvince', 'cmbCity', 'cmbArea'])) {
                    $query->addSelect("{$fieldContrastTrue[$k]} as city_name ");
                    $address_flag = false;
                } else {
                    if (!in_array("{$fieldContrastTrue['cmbProvince']} as city_name", $query->select)) {
                        if ($address_flag) {
                            $query->addSelect("{$fieldContrastTrue['cmbProvince']} as city_name");
                        }
                    }
                }
                $key .= $w;
                $str[] = "{$fieldContrastTrue[$k]}=:{$k}";
                $condition[":{$k}"] = $w;
            }
            $query->where(implode(' and ', $str), $condition);
        } else {
            $query->addSelect("{$fieldContrastTrue['cmbProvince']} as city_name");
        }
     

        //andWhere
        if (!empty($andWhere) && is_array($andWhere)) {
            foreach ($andWhere as $k=>$and) {
               if ($k === 'like') {
                   if (!empty($and) && is_array($and)) {
                       foreach ($and as $v) {
                           $query->andWhere(['like', $fieldContrastTrue[$v['field']], $v['value']]);
                           $key .= $v['value'];
                       }
                   }
               } elseif($k === 'between'){
                   $query->andWhere(["{$k}", "{$fieldContrastTrue[$and['field']]}", "{$and['value']['start']}", "{$and['value']['end']}"]);
                   $key .= $and['value']['start'] . $and['value']['end'];
               }
            }
        }
        //orWhere

        //group by
        if (!empty($group) && is_array($group)) {
            $query->groupBy(implode(', ', $group));
            $key .= implode('', $group);
        }

        //order by
        if (isset($params['sort']) && !empty($params['sort']) && is_array($params['sort'])) {
            $tem = [];
            foreach ($params['sort'] as $s=>$v) {
                array_push($tem,  "{$fieldContrastTrue[$s]} {$v}");
            }
            $query->orderBy(implode(', ', $tem));
            $key .= implode('', $tem);
        }
        //设立缓存根据sql;
        $sql = $query->createCommand()->getRawSql();
        $count = Yii::$app->cache->get(md5($sql.'page'));


        if ($count === false) {
            $count = $query->count();
            Yii::$app->cache->set(md5($sql.'page'), $count, self::$CACHING_TIME);
        }

        //page
        $page = new Pagination([
            'totalCount'=>$count,
            'pageSize'=>$params['page']['pageSize']
        ]);

        $page->setPage($params['page']['page']-1);
        $page->route = $params['page']['url'];

        $query->offset($page->offset);
        $query->limit($page->limit);
        $list = Yii::$app->cache->get(md5($sql));

        if ($list === false) {
            $list = $query->all();
            Yii::$app->cache->set(md5($sql), $list, self::$CACHING_TIME);
        }
        $row = array_map(function ($recode) {
            //$recode['create_time'] = substr($recode['create_time'], 0, strlen(date('Y-m-d')));
                return $recode;
        }, $list);
        return [
            'list'=>$row,
            'page'=>$page
        ];

    }

    /**过滤时间和like参数
     * @param array $condition
     * @return array
     */
    public static function filterTimeAndLike($condition = [])
    {
        $temp = [];
        if (empty($condition) || !is_array($condition)) return [];
        
        $completeTime = self::disposeAndWhere($condition);
        if (!empty($completeTime)) {
            $temp['between'] =[
                'field'=>'complete_time',
                'value'=>[
                    'start'=>$completeTime['between']['start'],
                    'end'=>$completeTime['between']['end'],
                ]
            ] ;
        }

        foreach ($condition as $k=>$v) {
             if(in_array($k, ['brand', 'car_type'])) {
                 if (!empty($v)) {
                     $temp['like'][] = [
                         'field'=>$k,
                         'value'=>$v
                     ];
                 }
            }
        }
        return $temp;
    }

    /**获取消耗与需求配件个数
     * @return array
     */
    public static function getCount()
    {
        $fields =[
            'o.complete_time',
            'o.create_time',
            'i.material_id',
            //'i.material_type',
            'o.user_car',
            'm.name as material_name',
            'mt.type as material_type',
            'mt.brand'
        ];
        $key = 'total';
        $cost = (new Query())
            ->select(['*'])
            ->from('store_purchasing_demand s')
            ->join('INNER JOIN', 'store_purchasing_material m', 's.id = m.dpd_id')
            ->count('m.dpd_id');
        $pur_count = Yii::$app->cache->get(md5($key));
        if ($pur_count === false) {
            $pur_count = (new Query())
                ->select($fields)
                ->from('order as o')
                ->join('inner join', 'order_item i', 'o.order_number=i.order_number')
                ->join('left join ', 'store s', 'o.store_id=s.id')
                ->join('left join ', 'material_type mt', 'mt.id=i.material_type_id')
                ->join('left join ', 'material m', 'm.id=mt.material_id')
                ->count();
            Yii::$app->cache->set(md5($key), $pur_count, self::$CACHING_TIME);
        }
        return [
            'cost_num'=>$cost,
            'pur_total'=>$pur_count
        ];
    }

    /**
     * @param $id
     * @param $status
     */
    public static function updateStatus($id, $status)
    {
        $model = StorePurchasingDemand::findOne($id);
        if ($model) {
            $model->status = $status;
            $model->save();
        }
        return ;
    }
}